package org.codehaus.activemq.gbean;

import javax.jms.JMSException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.geronimo.gbean.GBeanInfo;
import org.apache.geronimo.gbean.GBeanInfoFactory;
import org.apache.geronimo.gbean.GBeanLifecycle;
import org.apache.geronimo.gbean.WaitingException;
import org.codehaus.activemq.broker.BrokerContainer;
import org.codehaus.activemq.broker.impl.BrokerContainerImpl;

public class ActiveMQContainer
  implements GBeanLifecycle
{
  private Log log = LogFactory.getLog(getClass().getName());
  private final String brokerName;
  private BrokerContainer container;
  public static final GBeanInfo GBEAN_INFO=null;

  public ActiveMQContainer()
  {
    this.brokerName = null;
  }

  public ActiveMQContainer(String brokerName) {
    assert (brokerName != null);
    this.brokerName = brokerName;
  }

  public BrokerContainer getBrokerContainer() {
    return this.container;
  }

  public synchronized void doStart() throws WaitingException, Exception {
    if (this.container == null) {
      this.container = createContainer();
      this.container.start();
    }
  }

  public synchronized void doStop() throws WaitingException, Exception {
    if (this.container != null) {
      BrokerContainer temp = this.container;
      this.container = null;
      temp.stop();
    }
  }

  public synchronized void doFail() {
    if (this.container != null) {
      BrokerContainer temp = this.container;
      this.container = null;
      try {
        temp.stop();
      }
      catch (JMSException e) {
        this.log.info("Caught while closing due to failure: " + e, e);
      }
    }
  }

  protected BrokerContainer createContainer() throws Exception {
    return new BrokerContainerImpl(this.brokerName);
  }

  public static GBeanInfo getGBeanInfo()
  {
    return GBEAN_INFO;
  }

  static
  {
    //GBeanInfoFactory infoFactory = new GBeanInfoFactory("ActiveMQ Message Broker", ActiveMQContainer.class.getName());
   // infoFactory.addAttribute("brokerName", String.class, true);
   // infoFactory.addAttribute("BrokerContainer", BrokerContainer.class, false);
   // infoFactory.setConstructor(new String[] { "brokerName" });

    //GBEAN_INFO = infoFactory.getBeanInfo();
  }
}